import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const API_BASE_URL = 'http://localhost:8080/api' // 后端API基础URL

export const useAuthStore = defineStore('auth', () => {
  const router = useRouter()
  
  // State
  const user = ref(null)
  const token = ref(localStorage.getItem('token') || null)
  const isAuthenticated = ref(!!token.value) // 根据token是否存在初始化认证状态
  const loading = ref(false)

  // Getters
  const userRole = () => user.value?.role || null
  const isAdmin = () => userRole() === 'Admin'
  const isEmployee = () => userRole() === 'Employee'
  const isCustomer = () => userRole() === 'Customer'

  // Actions
  const login = async (credentials) => {
    loading.value = true
    try {
      const response = await axios.post(`${API_BASE_URL}/users/login`, {
        username: credentials.username,
        passwordHash: credentials.password, // 后端期望passwordHash
        role: credentials.role // 传递角色给后端
      })

      if (response.data.success) {
        token.value = response.data.token
        user.value = response.data.user // 后端返回的用户信息
        isAuthenticated.value = true
        localStorage.setItem('token', token.value)
        localStorage.setItem('user', JSON.stringify(user.value)); // 存储用户信息

        ElMessage.success('登录成功！')

        // 根据角色进行路由跳转
        switch (user.value.role) {
          case 'Admin':
            router.push('/admin/dashboard')
            break
          case 'Employee':
            router.push('/employee/dashboard')
            break
          case 'Customer':
            // 客户需要检查审核状态
              if (user.value.customerRegistrationStatus === 'Approved') {
              router.push('/customer/dashboard?tab=meetingRooms')
            } else {
              ElMessage.warning('您的客户账号正在审核中或已被拒绝，请联系管理员。')
              logout(); // 未通过审核的客户不允许登录
            }
            break
          default:
            ElMessage.error('未知角色，请联系管理员。')
            logout();
        }
      } else {
        ElMessage.error(response.data.message || '登录失败，请检查用户名或密码。')
        throw new Error(response.data.message || 'Login failed');
      }
    } catch (error) {
      console.error('Login error:', error);
      ElMessage.error(error.response?.data?.message || '登录失败，请稍后再试。')
      throw error
    } finally {
      loading.value = false
    }
  }

  const logout = () => {
    user.value = null
    token.value = null
    isAuthenticated.value = false
    localStorage.removeItem('token')
    localStorage.removeItem('user');
    router.push('/login')
    ElMessage.info('您已退出登录。')
  }

  const register = async (userData) => {
    loading.value = true
    try {
      const response = await axios.post(`${API_BASE_URL}/users/register`, {
        username: userData.username,
        fullName: userData.fullName,
        passwordHash: userData.passwordHash, // 保持与后端字段一致
        role: userData.role,
        phone: userData.phone,
        companyName: userData.companyName,
        email: userData.email
      })
      if (response.data) { // Assuming backend returns true on success
        ElMessage.success('注册成功！客户账号需等待管理员审核。')
        router.push('/login')
      } else {
        ElMessage.error('注册失败，请稍后再试。')
        throw new Error('Registration failed');
      }
    } catch (error) {
      console.error('Registration error:', error);
      ElMessage.error(error.response?.data?.message || '注册失败，用户名可能已存在。')
      throw error
    } finally {
      loading.value = false
    }
  }

  const checkAuth = async () => {
    if (!token.value) {
      isAuthenticated.value = false;
      user.value = null;
      return false;
    }

    try {
      console.log('Verifying token...');
      const response = await axios.get(`${API_BASE_URL}/users/verify-token`, {
        headers: {
          'Authorization': `Bearer ${token.value}`
        }
      });
      console.log('Token verification response:', response.data);

      if (response.data.valid) {
        if (response.data.user && response.data.user.userId && response.data.user.role) {
          // 确保关键用户信息存在
          user.value = response.data.user;
          isAuthenticated.value = true;
          localStorage.setItem('user', JSON.stringify(user.value));
          console.log('User authenticated:', user.value);
          return true;
        } else {
          console.error('User data missing required fields:', response.data.user);
          ElMessage.error('用户关键信息缺失，请重新登录');
          logout();
          return false;
        }
      }
    } catch (error) {
      console.error('Token验证失败:', error);
      // 网络错误时不自动登出，仅当明确token无效时才登出
      if (error.response?.status === 401) {
        logout();
      }
      return false;
    }
    
    // token无效时清除状态
    logout();
    return false;
  }

  // Initial check when the store is created
  checkAuth();

  return {
    user,
    token,
    isAuthenticated,
    loading,
    userRole,
    isAdmin,
    isEmployee,
    isCustomer,
    login,
    logout,
    register,
    checkAuth
  }
})
